require 'cgj.rb'

class Admin::OrdersController < Admin::BaseController
  before_action :set_order, only: [:show, :update_api_order_no]

  def index
    @orders = Order.paginate(page: params[:page] || 1, per_page: params[:per_page] || 15).order("updated_at desc")
  end

  def show
  end

  def search_master
    response = Cgj.fetch_users(params[:keyword])
    response = JSON.parse response.body
    render json: {
      status: 'ok',
      data: response
    }
  end

  def search_source
    response = Cgj.fetch_source(params[:type])
    response = JSON.parse response.body
    render json: {
      status: 'ok',
      data: response
    }
  end

  def edit_total_amount
    @order = Order.find params[:id]
  end

  def update_total_amount
    @order = Order.find params[:id]
    total_amount = params[:order][:total_money]

    if OrderService.update_total_amount(@order, total_amount)
      flash[:notice] = "修改订单总价成功"
      redirect_to admin_order_path(@order)
    else
      render action: :edit_total_amount
    end
  end

  def complete_order
    @order = Order.find params[:id]
    if @order.tail_payment?
      @order.to_install!
    elsif @order.install_pending?
      @order.complete!
    end
    redirect_to admin_order_path(@order)
  end

  def create_api_order
    response = Cgj.create_order(params[:order].as_json)
    response = JSON.parse response.body
    render json: {
      status: 'ok',
      data: response
    }
  end

  def update_api_order_no
    if @order.update(chuang_order_no: params[:chuang_order_no])
      render json: {
        status: 'ok',
        data: @order
      }
    else
      render json: {
        status: 'error',
        data: @order,
        msg: '订单出现了问题，请重试'
      }
    end
  end

  private

  def set_order
    @order = Order.find(params[:id])
  end

end
